package com.djsblog.service.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.djsblog.entity.Files;
import com.djsblog.entity.PageBean;
import com.djsblog.service.FilesService;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.tx.Tx;
/**
 * 文件事务接口实现
 * @author 但劲松
 *
 */
@Before(Tx.class)
public class FilesServiceImpl implements FilesService{

	public List<Files> find(Files s_files, PageBean pageBean) {
		StringBuffer sql = new StringBuffer("select * from files ");
		if(s_files!=null){
			if(StrKit.notBlank(s_files.getDel()))
				sql.append(" and del = '"+s_files.getDel()+"'");
			//模糊查询name
			if(StrKit.notBlank(s_files.getName()))
				sql.append(" and `key` like '%"+s_files.getName()+"%'");
			//mp3还是图片
			if(StrKit.notBlank(s_files.getType()))
				sql.append(" and TYPE LIKE '%"+s_files.getType()+"%' ");
			if(s_files.getCreated()!=null)
				sql.append(" order by `created` desc");
		}
		//分页
		if(pageBean!=null) sql.append(" limit "+pageBean.getStart()+","+pageBean.getPageSize());
		return Files.dao.find(sql.toString().replaceFirst(" and", " where"));
	}

	public long count(Files s_files) {
		StringBuffer sql = new StringBuffer("select count(*) as total from files ");
		if(s_files!=null){
			if(StrKit.notBlank(s_files.getDel()))
				sql.append(" and del = '"+s_files.getDel()+"'");
			//模糊查询name
			if(StrKit.notBlank(s_files.getName()))
				sql.append(" and `key` like '%"+s_files.getName()+"%'");
			//mp3还是图片
			if(StrKit.notBlank(s_files.getType()))
				sql.append(" and TYPE LIKE '%"+s_files.getType()+"%' ");
		}
		return Db.queryLong(sql.toString().replaceFirst(" and", " where"));
	}

	public boolean save(Files files) {
		try{
			if(files.getId() == null){
				files.setCreated(new Date());
				return files.save();
			}
			return files.update();
		}catch(Exception e){
			try {
				//执行失败回滚事务
				DbKit.getConfig().getConnection().rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			} 
		}
		return false;
	}

	public boolean deleteOrComeback(Long id, String del) {
		try{
			Files files = new Files();
			files.setId(id);
			files.setDel(del);
			return files.update();
		}catch(Exception e){
			try {
				//执行失败回滚事务
				DbKit.getConfig().getConnection().rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			} 
		}
		return false;
	}

	public Files getById(Long id) {
		return Files.dao.findById(id);
	}

}
